import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { registerMicroApps, start } from 'qiankun'

import App from './App.vue'
import router from './router'
import { qiankunConfig } from './micro/apps'
import { microApps, microAppsLifeCycles } from './micro/microApps'
import { initResponsive, setViewport } from './assets/responsive'

import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'

// 自动注册 Icon 组件
const modules = import.meta.glob('./components/icons/*.vue', { eager: true })
const iconComponents = Object.entries(modules).reduce(
  (components, [path, module]) => {
    // 获取文件名作为组件名（去掉路径和后缀）
    const componentName =
      path
        .split('/')
        .pop()
        ?.replace(/\.\w+$/, '') ?? ''
    if (componentName) {
      components[componentName] = (module as any).default
    }
    return components
  },
  {} as Record<string, any>,
)

// 初始化响应式配置
setViewport()
initResponsive()

// 创建主应用
const app = createApp(App)

// 注册所有图标组件为全局组件
Object.entries(iconComponents).forEach(([name, component]) => {
  app.component(name, component)
})

// 3. 创建并注册Pinia（必须在所有store使用前注册）
try {
  const pinia = createPinia()
  app.use(pinia)
  console.log('Pinia已成功注册')
} catch (error) {
  console.error('Pinia注册失败:', error)
  throw error
}

// 4. 注册其他插件
app.use(router)
app.use(ElementPlus)

app.use(router)

// 挂载主应用
app.mount('#app')

// 注册微应用
registerMicroApps(microApps, microAppsLifeCycles)

// 启动 qiankun
start(qiankunConfig)
